import json
import os

import rou.constants as rc


def get_gantry_info():
    gantry_path = rc.DEFAULT_SCENE_GANTRY_PATH
    gty_path = os.path.join(gantry_path, rc.DEFAULT_GANTRY_NAME)
    with open(gty_path, "r", encoding="utf-8") as f:
        data = f.read()
    return json.loads(data)


def get_gantry_info_HTF():
    gantry_path = rc.DEFAULT_SCENE_GANTRY_PATH
    gty_path = os.path.join(gantry_path, rc.DEFAULT_GANTRY_NAME_HTF)
    with open(gty_path, "r", encoding="utf-8") as f:
        data = f.read()
    return json.loads(data)


def get_speed_limit_points(frame_info: dict, speed_point_limit: list, speeds: list):
    """
    frame_info: 门架编号以及其所在的经纬度
    speed_point_limit：门架编号
    speeds：门架限速值
    return get_limit_points , speed_limit, speed_point_limit
    返回：排序后的门架经纬度、限速值、门架编号
    """
    get_limit_points = []
    speed_limit = []
    # 首先对门架进行排序
    for i in range(len(speed_point_limit)):
        # 最后 i 个元素已经排序好了，因此可以减少内层循环次数
        for j in range(0, len(speed_point_limit) - i - 1):
            # 如果前一个元素比后一个元素大，则交换它们的位置
            if speed_point_limit[j].split("-")[1] > speed_point_limit[j + 1].split("-")[1]:
                speed_point_limit[j], speed_point_limit[j + 1] = speed_point_limit[j + 1], speed_point_limit[j]
                speeds[j], speeds[j + 1] = speeds[j + 1], speeds[j]

    for i in range(len(speed_point_limit)):
        if speed_point_limit[i] not in frame_info.keys():
            continue
        point = frame_info[speed_point_limit[i]]
        speed = speeds[i]
        frame_point = {
            "lon": point['long'],
            "lat": point['lat']
        }
        get_limit_points.append(frame_point)
        speed_limit.append(speed)
    # print("返回值",get_limit_points, speed_limit, speed_point_limit)

    return get_limit_points, speed_limit, speed_point_limit
